package com.apeli.design;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * subject
 *
 * @author liming
 * @date 2023 06 07
 */
//@Component
public class MessagePublisher {

    /**
     * 消费者列表
     */
    private List<Consumer> consumerList;

    /**
     * 消息
     */
    private Event event;

    public MessagePublisher() {
        this.consumerList = new ArrayList<>();
    }


    /**
     * 发布事件
     *
     * @param event 事件
     */
    public void publishEvent(Event event) {
        this.event = event;
        notifyAllObserver(event);
    }

    /**
     * 注册消费者
     *
     * @param consumer 消费者
     */
    public void register(Consumer consumer) {
        consumerList.add(consumer);
    }

    /**
     * 通知所有观察者
     *
     * @param event 状态
     */
    private void notifyAllObserver(Event event) {
        consumerList.forEach(consumer -> {
            new Thread(() -> consumer.consumer(event)).start();
        });
    }

    @Data
    @AllArgsConstructor
    public static class Event<T> {
        private Integer eventId;

        private T eventContent;
    }
}
